package com.software.frontend.firstPage.fragment;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_DRAGGING;

import android.app.ActivityOptions;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.software.frontend.R;
import com.software.frontend.firstPage.YouYouJIanDetailsPageActivity;
import com.software.frontend.firstPage.adapter.OnRecyclerItemClickListener;
import com.software.frontend.firstPage.adapter.RecAdapter;
import com.software.frontend.firstPage.entity.Post;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RecFragment extends Fragment {

    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "img";

    private String title;
    private int img;

    private RecyclerView recyclerView;
    private List<Post> posts = new ArrayList<>();
    private RecAdapter recAdapter;
    public int[] firstStaggeredGridPosition={0,0};
    public int[] lastStaggeredGridPosition={0,0};

    private SmartRefreshLayout refreshLayout;
    private boolean isRefresh = true;
    private final int REFRESH = 1;
    private int currentNum = 0;
    private int pageSize = 7;
    private Handler myHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程的消息
            switch (msg.what) {
                case REFRESH:
                    //刷新recycleView
                    recAdapter.notifyDataSetChanged();
                    //结束刷新和加载动画
                    if (isRefresh) {
                        refreshLayout.finishRefresh();
                    }else {
                        refreshLayout.finishLoadMore();
                    }
                    break;
            }
        }
    };

    public static RecFragment newInstance(String title) {
        RecFragment fragment = new RecFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            title = getArguments().getString(ARG_PARAM1);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_you_you_j_ian_rec, container, false);
        recyclerView = view.findViewById(R.id.rec_recycler);
        refreshLayout = view.findViewById(R.id.youYouJIan_srl);
        getData();
        setListener();
        recAdapter = new RecAdapter(this.getActivity(), posts);
        recAdapter.setHasStableIds(true);

        //initData();
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
//        layoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(recAdapter);
        //设置RecAdapter的Item监听
        recAdapter.setOnRecyclerItemClickListener(new OnRecyclerItemClickListener() {
            @Override
            public void onItemClick(int Position, List<Post> datas) {
                /* 跳转至另一个activity */
                Intent intent=new Intent(getActivity(), YouYouJIanDetailsPageActivity.class);
                //传递相应的参数
                Bundle bundle=new Bundle();
                Post post = posts.get(Position);
                bundle.putSerializable("post", post);
                intent.putExtras(bundle);

                //启用共享组件的activity过渡
                //所选择的共享元件，这个元件是当前页面的元件
                //获取item的ViewHolder
                Log.d("myposition-firstPo", Arrays.toString(firstStaggeredGridPosition));
                Log.d("myposition-actPo", String.valueOf(Position));
                Log.d("myposition-lastPo", Arrays.toString(lastStaggeredGridPosition));
                //因为我使用的是StaggeredGridLayoutManager
                RecyclerView.LayoutManager layoutManager1 = recyclerView.getLayoutManager();
                //由于瀑布流是两列，这里是为了获得处在页面的最小值
                int realFirstPosition=Math.min(firstStaggeredGridPosition[0],firstStaggeredGridPosition[1]);
                RecAdapter.MyVideoHolder myVideoHolder = (RecAdapter.MyVideoHolder) recyclerView.getChildViewHolder(recyclerView.getChildAt(Position-realFirstPosition));
                ImageView rec_info_image = myVideoHolder.imageView;

                ActivityOptions options = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    options = ActivityOptions.makeSceneTransitionAnimation(getActivity(),
                            Pair.create(rec_info_image, "rec_info_image"));
                }
                startActivity(intent, options.toBundle());
            }
        });

        //设置recycleView的滚动监听
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE || newState == SCROLL_STATE_DRAGGING) {
                    // DES: 找出当前可视Item位置
                    RecyclerView.LayoutManager layoutManager2 = recyclerView.getLayoutManager();
                    if (layoutManager2 instanceof StaggeredGridLayoutManager) {
                        Log.d("myposition-ac","scrool");
                        StaggeredGridLayoutManager linearManager = (StaggeredGridLayoutManager) layoutManager2;
                        linearManager.findFirstVisibleItemPositions(firstStaggeredGridPosition);
                        linearManager.findLastVisibleItemPositions(lastStaggeredGridPosition);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        return view;
    }

    private void setListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时回调，需要请求最新的数据
                isRefresh = true;
                currentNum = 0;
                getData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //上拉加载更多时回调，需要请求更多的数据，分页查询
                isRefresh = false;
                currentNum++;//页码加1
                getData();
            }
        });
    }

    private void getData() {
        //向服务端传递当前请求的页码，每页显示的图书的条数
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getString(R.string.localhost) + "post/findPostInfo?page=" + currentNum + "&size=" + pageSize )
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String postStr = response.body().string();
                Gson gson = new Gson();
                //为了避免泛型擦除
                Type type = new TypeToken<List<Post>>(){}.getType();
                List<Post> postList = gson.fromJson(postStr, type);
                Log.e("pst", postStr);
                //Log.e("posts",posts.get(0).toString());
                //添加到数据源中
                if (isRefresh) {
                    posts.clear();
                    posts.addAll(postList);
                }else {
                    posts.addAll(postList);
                }
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.what = REFRESH;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}
